<template>
  <div class="document-share-container">
    <div class="document-main">
      <!-- 左侧目录树 -->
      <div class="document-tree-col" :style="{ width: leftWidth + 'px' }">
        <div class="document-tree-container">
          <el-card shadow="never" class="tree-card">
            <template #header>
              <div class="card-header">
                <span>目录</span>
                <div class="tree-header-actions">
                  <el-icon @click="handleAddDocument" :size="16"><Plus /></el-icon>
                  <el-icon @click="refreshTree" :size="16"><Refresh /></el-icon>
                </div>
              </div>
            </template>
            <div class="tree-content">
              <el-tree
                ref="treeRef"
                :data="documentTree"
                node-key="_id"
                :props="treeProps"
                :expand-on-click-node="false"
                :highlight-current="true"
                :default-expanded-keys="defaultExpandedKeys"
                @node-click="handleNodeClick"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <el-icon v-if="data.type === 'folder'"><Folder /></el-icon>
                    <el-icon v-else><Document /></el-icon>
                    <span class="tree-node-label">{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 拖拽条 -->
      <div class="drag-divider" @mousedown="startDrag"></div>

      <!-- 右侧内容区 -->
      <div class="document-content-col" :style="{ width: rightWidth + 'px' }">
        <!-- 顶部操作按钮区 -->
        <div class="document-actions-bar" v-if="currentDocument._id">
          <div class="document-title">
            <h2>{{ currentDocument.name }}</h2>
            <div class="document-info">
              <span class="view-count">
                <el-icon><View /></el-icon>
                {{ currentDocument.viewCount || 0 }} 次浏览
              </span>
              <span class="like-count" @click="handleLike">
                <el-icon :class="{ liked: isLiked }"><Star /></el-icon>
                {{ currentDocument.likeCount || 0 }}
              </span>
            </div>
          </div>
          <div class="document-actions">
            <el-tooltip content="编辑" placement="top">
              <el-icon :size="20" @click="handleEdit"><Edit /></el-icon>
            </el-tooltip>
            <el-tooltip content="预览" placement="top">
              <el-icon :size="20" @click="handlePreview"><View /></el-icon>
            </el-tooltip>
            <el-tooltip content="历史版本" placement="top">
              <el-icon :size="20" @click="handleHistory"><Clock /></el-icon>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-icon :size="20" @click="handleDelete"><Delete /></el-icon>
            </el-tooltip>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="document-content-area">
          <!-- 文档详情卡片 -->
          <div v-if="currentDocument._id" shadow="never" class="document-detail-card">
            <!-- 文档内容显示 -->
            <div class="document-content-display" v-html="currentDocument.content"></div>
          </div>

          <!-- 空状态 -->
          <el-card v-else shadow="never" class="empty-card">
            <el-empty description="请选择或创建一个文档">
              <el-button type="primary" @click="handleAddDocument">新增文档</el-button>
            </el-empty>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" :title="currentDocument.name" width="80%" top="50px" class="preview-dialog">
      <div class="preview-content" v-html="currentDocument.content"></div>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增文档" width="500px">
      <el-form :model="addForm" label-width="80px" ref="addFormRef">
        <el-form-item label="文档标题" prop="name" :rules="[{ required: true, message: '请输入文档标题', trigger: 'blur' }]">
          <el-input v-model="addForm.name" placeholder="请输入文档标题" />
        </el-form-item>
        <el-form-item label="父级节点" prop="pid">
          <el-tree-select
            v-model="addForm.pid"
            :data="documentTree"
            node-key="_id"
            :props="treeProps"
            check-strictly
            clearable
            placeholder="请选择父级节点（可选）"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddDocument">确定</el-button>
      </template>
    </el-dialog>

    <!-- 历史版本抽屉 -->
    <version-history-drawer ref="versionHistoryDrawerRef" @version-restored="handleVersionRestored" />

    <!-- 编辑抽屉 -->
    <doc-edit-drawer ref="docEditDrawerRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { Folder, Document, Refresh, View, Edit, Delete, Star, Plus, Clock } from "@element-plus/icons-vue";
import DocEditDrawer from "./docEditDrawer.vue";
import VersionHistoryDrawer from "./versionHistoryDrawer.vue";
import { ShareDoc } from "./types/document";
import apiService from "@/api/services/apiService";

// 树组件引用
const treeRef = ref();

// 新增表单引用
const addFormRef = ref<FormInstance>();

// 编辑抽屉引用
const docEditDrawerRef = ref();

// 历史版本抽屉引用
const versionHistoryDrawerRef = ref();

// 树属性配置
const treeProps = {
  label: "name",
  children: "children"
};

// 默认展开的节点
const defaultExpandedKeys = ref<string[]>([]);

// 文档树数据
const documentTree = ref<ShareDoc[]>([]);

// 当前选中文档
const currentDocument = ref<ShareDoc>({
  id: "",
  name: "",
  content: "",
  viewCount: 0,
  children: []
});

// 新增表单
const addForm = reactive({
  name: "",
  pid: ""
});

// 预览对话框可见性
const previewVisible = ref(false);

// 新增对话框可见性
const addDialogVisible = ref(false);

// 是否已点赞
const isLiked = ref(false);

// 拖拽相关
const leftWidth = ref(280);
const rightWidth = ref(0);
const isDragging = ref(false);
const startX = ref(0);
const startLeftWidth = ref(0);

// 初始化拖拽相关数据
onMounted(() => {
  // 初始化右侧宽度
  rightWidth.value = window.innerWidth - leftWidth.value - 60; // 60为padding和边距

  // 监听窗口大小变化
  window.addEventListener("resize", handleResize);

  // 添加全局事件监听器
  document.addEventListener("mousemove", doDrag);
  document.addEventListener("mouseup", stopDrag);
});

// 窗口大小变化处理
const handleResize = () => {
  rightWidth.value = window.innerWidth - leftWidth.value - 60;
};

// 开始拖拽
const startDrag = (e: MouseEvent) => {
  isDragging.value = true;
  startX.value = e.clientX;
  startLeftWidth.value = leftWidth.value;

  // 添加全局事件监听器
  document.addEventListener("mousemove", doDrag);
  document.addEventListener("mouseup", stopDrag);

  // 防止文本选中
  document.body.style.userSelect = "none";
  document.body.style.cursor = "col-resize";

  // 防止事件冒泡
  e.preventDefault();
};

// 执行拖拽
const doDrag = (e: MouseEvent) => {
  if (!isDragging.value) return;

  const dx = e.clientX - startX.value;
  const newLeftWidth = startLeftWidth.value + dx;

  // 限制最小宽度
  if (newLeftWidth >= 220 && newLeftWidth <= window.innerWidth - 220) {
    leftWidth.value = newLeftWidth;
    rightWidth.value = window.innerWidth - newLeftWidth - 60;
  }

  // 防止事件冒泡
  e.preventDefault();
};

// 停止拖拽
const stopDrag = () => {
  isDragging.value = false;

  // 恢复样式
  document.body.style.userSelect = "";
  document.body.style.cursor = "";

  // 移除事件监听器
  document.removeEventListener("mousemove", doDrag);
  document.removeEventListener("mouseup", stopDrag);
};

// 清理事件监听器
const cleanupListeners = () => {
  document.removeEventListener("mousemove", doDrag);
  document.removeEventListener("mouseup", stopDrag);
  window.removeEventListener("resize", handleResize);
};

// 组件卸载时清理
onUnmounted(() => {
  cleanupListeners();
});

// 在 mounted 钩子中添加事件监听器
onMounted(() => {
  // 初始化右侧宽度
  rightWidth.value = window.innerWidth - leftWidth.value - 60; // 60为padding和边距

  // 监听窗口大小变化
  window.addEventListener("resize", handleResize);

  loadDocumentTree();
});

// 加载文档树
const loadDocumentTree = async () => {
  try {
    // 指定返回列，不返回content字段以提高性能
    const res = await apiService.findTree<ShareDoc[]>(
      "shareDoc",
      {},
      {
        sort: { sort: 1 },
        select: "name _id pid type viewCount likeCount children" // 不返回content字段
      }
    );
    documentTree.value = res.data || [];

    // 如果有数据，默认展开第一个节点
    if (res.data && res.data.length > 0) {
      defaultExpandedKeys.value = [res.data[0]._id || ""];
      // 默认选中第一个节点并加载其内容
      nextTick(() => {
        treeRef.value?.setCurrentKey(res.data[0]._id);
        handleNodeClick(res.data[0]);
      });
    }
  } catch (error) {
    console.error("加载文档树失败:", error);
    ElMessage.error("加载文档树失败");
  }
};

// 刷新树
const refreshTree = () => {
  loadDocumentTree();
};

// 节点点击事件 - 点击时再加载内容
const handleNodeClick = async (data: ShareDoc) => {
  try {
    // 如果是文件节点且没有content，则加载完整内容
    if (data.type !== "folder" && !data.content) {
      const res = await apiService.findOne<ShareDoc>("shareDoc", { _id: data._id });
      if (res.data) {
        currentDocument.value = res.data;
      } else {
        currentDocument.value = data;
      }
    } else {
      currentDocument.value = data;
    }
  } catch (error) {
    console.error("加载文档内容失败:", error);
    currentDocument.value = data;
    ElMessage.error("加载文档内容失败");
  }
  // 重置点赞状态
  isLiked.value = false;
};

// 新增文档
const handleAddDocument = () => {
  // 重置表单
  addForm.name = "";
  addForm.pid = "";
  addDialogVisible.value = true;
};

// 确认新增文档
const confirmAddDocument = async () => {
  if (!addForm.name) {
    ElMessage.warning("请输入文档标题");
    return;
  }

  try {
    const newDoc = {
      id: Date.now().toString(), // 简单生成ID
      name: addForm.name,
      content: "",
      viewCount: 0,
      pid: addForm.pid || undefined,
      createDate: new Date(),
      lastModifyDate: new Date()
    };

    await apiService.save("shareDoc", newDoc);
    ElMessage.success("新增成功");
    addDialogVisible.value = false;

    // 重新加载树
    loadDocumentTree();
  } catch (error) {
    console.error("新增失败:", error);
    ElMessage.error("新增失败");
  }
};

// 预览文档
const handlePreview = () => {
  previewVisible.value = true;
};

// 编辑文档
const handleEdit = () => {
  // 调用抽屉组件的acceptParams方法
  docEditDrawerRef.value.acceptParams({
    row: currentDocument.value,
    api: apiService.updateById,
    updateCurShareDoc: (content: string | undefined) => {
      currentDocument.value.content = content || "";
    },
    refreshTreeItem: (updatedDoc: ShareDoc) => {
      // 只更新修改的那条记录，而不是整个刷新树
      updateTreeItem(documentTree.value, updatedDoc);
      // 同时更新当前文档
      currentDocument.value = { ...currentDocument.value, ...updatedDoc };
    }
  });
};

// 更新树中的特定项
const updateTreeItem = (tree: ShareDoc[], updatedDoc: ShareDoc) => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i]._id === updatedDoc._id) {
      // 只更新非content字段，保持树的性能
      tree[i] = {
        ...tree[i],
        name: updatedDoc.name,
        lastModifyDate: updatedDoc.lastModifyDate,
        viewCount: updatedDoc.viewCount,
        likeCount: updatedDoc.likeCount
      };
      break;
    }
    if (tree[i].children && tree[i].children.length > 0) {
      updateTreeItem(tree[i].children, updatedDoc);
    }
  }
};

// 查看历史版本
const handleHistory = () => {
  if (!currentDocument.value._id) {
    ElMessage.warning("请先选择一个文档");
    return;
  }

  // 调用历史版本抽屉组件的acceptParams方法
  versionHistoryDrawerRef.value.acceptParams({
    catalogId: currentDocument.value._id
  });
};

// 处理版本恢复事件
const handleVersionRestored = () => {
  // 重新加载当前文档内容
  handleNodeClick(currentDocument.value);
};

// 删除文档
const handleDelete = () => {
  if (!currentDocument.value._id) return;

  ElMessageBox.confirm("确定要删除该文档吗？此操作不可恢复", "提示", {
    type: "warning"
  })
    .then(async () => {
      try {
        await apiService.deleteById("shareDoc", currentDocument.value._id);
        ElMessage.success("删除成功");
        // 重新加载树
        loadDocumentTree();
        // 清空当前文档
        currentDocument.value = {
          id: "",
          name: "",
          content: "",
          viewCount: 0,
          children: []
        };
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 点赞功能
const handleLike = async () => {
  if (!currentDocument.value._id) return;

  // 切换点赞状态
  isLiked.value = !isLiked.value;

  try {
    // 更新点赞数
    const updatedDoc = {
      ...currentDocument.value,
      likeCount: (currentDocument.value.likeCount || 0) + (isLiked.value ? 1 : -1)
    };

    await apiService.updateById("shareDoc", updatedDoc);
    currentDocument.value.likeCount = updatedDoc.likeCount;
    ElMessage.success(isLiked.value ? "点赞成功" : "取消点赞");
  } catch (error) {
    console.error("点赞失败:", error);
    ElMessage.error("点赞失败");
    // 失败时恢复状态
    isLiked.value = !isLiked.value;
  }
};
</script>

<style scoped lang="scss">
.document-share-container {
  height: calc(100vh - 150px);
  overflow: hidden;
  .document-main {
    display: flex;
    height: 100%;
    overflow: hidden;
    .document-tree-col {
      flex-shrink: 0;
      height: 100%;
      .document-tree-container {
        height: 100%;
        .tree-card {
          display: flex;
          flex-direction: column;
          height: 100%;
          :deep(.el-card__body) {
            flex: 1;
            padding: 0;
            .tree-content {
              display: flex;
              flex-direction: column;
              height: 100%;
              .el-tree {
                flex: 1;
                padding: 10px;
                overflow: auto;
              }
            }
          }
        }
      }
    }
    .drag-divider {
      position: relative;
      z-index: 10;
      flex: 0 0 5px;
      width: 5px;
      height: 100%;
      cursor: col-resize;
      background-color: var(--el-border-color);
      transition: background-color 0.3s;
      &:hover {
        background-color: var(--el-color-primary);
      }
      &::before {
        position: absolute;
        top: 0;
        left: -2px;
        width: 9px;
        height: 100%;
        cursor: col-resize;
        content: "";
      }
    }
    .document-content-col {
      display: flex;
      flex: 1;
      flex-direction: column;
      height: 100%;
      overflow: hidden;
      .document-actions-bar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 20px;
        background-color: var(--el-bg-color);
        border-bottom: 1px solid var(--el-border-color);
        .document-title {
          flex: 1;
          h2 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
          }
          .document-info {
            display: flex;
            gap: 15px;
            align-items: center;
            margin-top: 8px;
            .view-count,
            .like-count {
              display: flex;
              gap: 5px;
              align-items: center;
              font-size: 13px;
              color: var(--el-text-color-secondary);
            }
            .like-count {
              cursor: pointer;
              .el-icon {
                color: var(--el-text-color-secondary);
                &.liked {
                  color: #f56c6c;
                }
              }
            }
          }
        }
        .document-actions {
          display: flex;
          .el-icon {
            display: inline-block;
            padding: 4px;
            margin: 0 4px;
            font-size: 24px;
            font-weight: 200;
            vertical-align: text-bottom;
            cursor: pointer;
            &:hover {
              font-weight: 600;
              color: red;
            }
          }
        }
      }
      .document-content-area {
        display: flex;
        flex: 1;
        flex-direction: column;
        min-height: 400px; // 确保内容区域有最小高度
        padding: 0; // 去掉边距
        overflow: hidden; // 确保滚动条正常工作
        .document-detail-card {
          flex: 1;
          min-height: 100%;
          background-color: var(--el-bg-color);
          border: none; // 去掉卡片边框
          border-radius: 0; // 去掉圆角
          .document-content-display {
            flex: 1;
            min-height: 300px;
            padding: 20px; // 在内容显示区域添加内边距
            overflow: auto; // 确保内容区域有滚动条

            // 富文本内容样式
            :deep(img) {
              max-width: 100%;
            }
            :deep(pre) {
              padding: 10px;
              overflow: auto;
              background-color: var(--el-fill-color-light);
              border-radius: 4px;
            }
          }
        }
        .empty-card {
          display: flex;
          flex: 1;
          align-items: center;
          justify-content: center;
          min-height: 400px;
          border: none; // 去掉卡片边框
          border-radius: 0; // 去掉圆角
        }
      }
    }
  }
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .tree-header-actions {
      .el-icon {
        display: inline-block;
        padding: 4px;
        margin: 0 4px;
        font-size: 16px;
        font-weight: 200;
        vertical-align: text-bottom;
        cursor: pointer;
        &:hover {
          font-weight: 600;
          color: red;
        }
      }
    }
  }
  .custom-tree-node {
    display: flex;
    gap: 5px;
    align-items: center;
    .tree-node-label {
      flex: 1;
    }
  }
  .preview-dialog {
    .preview-content {
      min-height: 500px;
      padding: 20px;

      // 富文本预览样式
      :deep(img) {
        max-width: 100%;
      }
      :deep(pre) {
        padding: 10px;
        overflow: auto;
        background-color: var(--el-fill-color-light);
        border-radius: 4px;
      }
    }
  }
}
</style>
